package org.bt.common.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.Optional;

/**
 * @author BridgeBai
 * @Description: 自定义填充公共字段
 * @date 2021/9/6 14:16
 */
@Component
public class DbMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     */
    private final static String CREATE_TIME = "createTime";
    /**
     * 修改时间
     */
    private final static String MODIFY_TIME = "modifyTime";
    /**
     * 创建人员
     */
    private final static String CREATE_USER = "createUser";
    /**
     * 修改人员
     */
    private final static String MODIFY_USER = "modifyUser";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (StpUtil.isLogin() && metaObject.hasSetter(CREATE_USER) && metaObject.hasSetter(MODIFY_USER)) {
            Optional<Object> opt = Optional.ofNullable(StpUtil.getExtra("id"));
            opt.ifPresent(o -> {
                setFieldValByName(CREATE_USER, String.valueOf(o), metaObject);
                setFieldValByName(MODIFY_USER, String.valueOf(o), metaObject);
            });
        }
        setFieldValByName(CREATE_TIME, new Timestamp(System.currentTimeMillis()), metaObject);
        setFieldValByName(MODIFY_TIME, new Timestamp(System.currentTimeMillis()), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (StpUtil.isLogin() && metaObject.hasSetter(MODIFY_USER)) {
            Optional<Object> opt = Optional.ofNullable(StpUtil.getExtra("id"));
            opt.ifPresent(o -> setFieldValByName(MODIFY_USER, String.valueOf(o), metaObject));
            setFieldValByName(MODIFY_TIME, new Timestamp(System.currentTimeMillis()), metaObject);
        }
    }
}
